<template>
  <div v-loading="allLoading" class="detail">
    <DataDisplay :data-list="dataList" type="oneCell" style="margin-bottom: 20px;" />

    <div>
      <div v-if="!showMobilePage" class="opeator-bar">
        <div class="flex-1">
          <FilterInput ref="FilterToolRef" v-model="paramsObj" :filter-list="filterList" show-search-btn @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus" />
        </div>
        <div>
          <div class="opeator-tool">
            <div class="tip-text"><span>点击获取最新数据</span></div>
            <el-button
              :loading="updateBtnLoading"
              type="primary"
              class="btn"
              size="small"
              @click="handleUpdate">更新结算数据</el-button>
            <el-button
              :loading="batchSettleLoading"
              type="primary"
              class="btn"
              size="small"
              @click="handleAllSettle">一键结算</el-button>
            <MoreOpeator
              ref="moreOperateRef"
              :list="[
                {
                  label:'导出明细',exportApi:'/admin/account/settle/export',
                  refName: 'exportRef', isBeforeExport: true,
                  exportName:'结算明细列表', beforeExport: exportBeforeExport, type: 'export'
                },
              ]"
            />
          </div>
        </div>
      </div>
      <div v-loading="listLoading" class="table-wrap">
        <u-table
          v-if="list.items.length > 0"
          ref="settleTableRef"
          :data="list.items"
          :row-class-name="tableRowClassName"
          :height="setTableHeight"
          :row-height="rowHeight()"
          :border="true"
          beautify-table
          header-drag-style
          use-virtual
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          @select="selectTable"
          @select-all="selectTable"
          @sort-change="sortMethod">
          <u-table-column
            :fixed="selectFixed"
            align="center"
            type="selection"
            width="50"/>
          <u-table-column label="账号" min-width="120" prop="account" sortable="custom">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.account" />
            </template>
          </u-table-column>
          <u-table-column label="下单平台" width="120" prop="platform" sortable="custom">
            <template slot-scope="scope">
              <div class="flex-center">
                <PlatformIcon :data="scope.row.platform" />
                {{ scope.row.platform || '--' }}
              </div>
            </template>
          </u-table-column>
          <u-table-column align="right" label="结算金额(元)" prop="settleAmount" sortable="custom" min-width="140">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.settleAmount" :price="scope.row.settleAmount / 100" />
            </template>
          </u-table-column>
          <u-table-column label="达人到手金额(元)" align="right" prop="receivedAmount" sortable="custom" width="160">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.receivedAmount" :price="scope.row.receivedAmount / 100" />
            </template>
          </u-table-column>
          <u-table-column label="成本来源" prop="costSource" sortable="custom" min-width="130">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.costSourceId | supplierCostBelong" />
            </template>
          </u-table-column>
          <u-table-column label="合作运营方" prop="cooperation" sortable="custom" width="160">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.cooperation" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width:200px;">{{ scope.row.cooperation }}</div>
                <div class="ellipsis" style="cursor:pointer;color:#406EFF;" @click="toSupplierDetail(scope.row.cooperationId)">{{ scope.row.cooperation }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column label="供应商" min-width="130" prop="supplier" sortable="custom">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.supplier" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width:200px;">{{ scope.row.supplier }}</div>
                <div class="ellipsis" style="cursor:pointer;color:#406EFF;" @click="toSupplierDetail(scope.row.supplierId)">{{ scope.row.supplier }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column label="操作" fixed="right">
            <template slot-scope="scope">
              <div style="display:flex">
                <div :class="{'disable': settleLoading}" class="button-text" @click="handleSettle(scope.row)">结算<i v-if="settleLoading && scope.row.id === currentSettleId" class="el-icon-loading"/></div>
              </div>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else/>
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
        <el-pagination
          v-show="list.total > 0"
          :current-page.sync="page"
          :page-size="perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[10, 20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination>
        <div v-if="!showMobilePage" class="bottom-flex">
          <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
          <div style="flex:1;" />
          <el-button class="back-btn cancel-btn-style" type="info" size="small" @click="handleBack">返回</el-button>
          <el-pagination
            :current-page.sync="page"
            :page-size="perPage"
            :total="list.total"
            :small="true"
            :page-sizes="[10, 20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <template v-else>
          <FilterInput ref="FilterToolRef" v-model="paramsObj" :filter-list="filterList" show-mobile-icon show-search-btn @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus" />
          <MoreOpeator
            ref="moreOpeatorRef"
            :list="[
              { label: '导出明细', exportApi: '/admin/account/settle/export', exportName: '账号结算单列表', beforeExport: exportBeforeExport, type: 'export' },
              { label:'更新结算数据', handelClick: () => { handleUpdate() }},
              { label: '返回', handelClick: handleBack }
            ]"
            show-mobile-icon
          />
          <createBtn
            mobile-table
            text="一键发起结算"
            @click.native="handleAllSettle"/>
        </template>
      </fixed-pagination>
    </div>
    <BatchDialog ref="BatchDialog" :batch-settle-info="batchSettleInfo" @handleSubmit="batchSettle"/>
    <LoadingDialog ref="LoadingDialog" :batch-settle-info="batchSettleInfo"/>
    <TipDialog ref="TipDialog" :batch-settle-info="batchSettleInfo" @searchFailAccount="searchFailAccount"/>
    <UpdateDialog
      :visible="updateVisible"
      :id="id"
      :follow-users="followUsers"
      :time="timeData.createOrderTime"
      @closeDialog="closeUpdateDialog"
      @updateData="updateData"
      @btnStatus="btnStatus"/>
  </div>
</template>

<script>
// components
import DataDisplay from '@/components/Common/baseComponent/dataDisplay';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import BatchDialog from '@/views/todo/components/batchDialog';
import LoadingDialog from '@/views/todo/components/loadingDialog';
import TipDialog from '@/views/todo/components/tipDialog';
import PlatformIcon from '@/components/Common/platformIcon';
import BtnGroup from '@/components/Common/baseComponent/btnGroup';
import UpdateDialog from './updateDialog';
import createBtn from '@/components/Common/baseComponent/createBtn';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { getSettleData, batchSettle, batchSettleStatus, getSettleTime } from '@/api/todo';
import { platformList } from '@/api/select';
import { accountSettleInfo } from '@/api/supplier';
import { supplierCostBelong } from '@/filters/status';
import { mapState } from 'vuex';

// imgs
import icon_16 from '@/assets/dataDisplay/icon_16.png';
import icon_17 from '@/assets/dataDisplay/icon_17.png';
import icon_20 from '@/assets/dataDisplay/icon_20.png';
import icon_21 from '@/assets/dataDisplay/icon_21.png';

export default {
  components: { DataDisplay, EmptyPlaceholder, PlatformIcon, BatchDialog,
    LoadingDialog, TipDialog, UpdateDialog, BtnGroup, createBtn, MoreOpeator
  },
  filters: { supplierCostBelong },
  mixins: [tableSelections, TableAdaptive, mobileTable],
  data() {
    return {
      allLoading: false,
      platformOption: [],
      costOption: [
        { value: 0, label: '渠道订单' },
        { value: 1, label: '项目订单' },
        { value: 2, label: '商务订单' },
        { value: 3, label: '营销授权' },
        { value: 4, label: '电商销售' },
        { value: 5, label: '项目渠道单' }
      ],
      rangeKeyArr: [
        { attr: 'settleAmount', start: 'settleAmountStart', end: 'settleAmountEnd', type: 'moneyFixed' },
        { attr: 'receivedAmount', start: 'receivedAmountStart', end: 'receivedAmountEnd', type: 'moneyFixed' }
      ],
      listLoading: false,
      paramsObj: {},
      list: {
        items: [],
        page: 1,
        perPage: 10,
        total: 0,
        isInint: true
      },
      page: 1,
      perPage: 10,
      tableRefName: 'settleTableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      ids: '',
      isUmyTable: true,
      timer: null,
      batchSettleInfo: {},
      sortName: '',
      sortType: -1,
      updateVisible: false,
      id: '',
      timeData: {},
      followUsers: '',
      updateBtnLoading: false,
      settleLoading: false,
      currentSettleId: '',
      batchSettleLoading: false,
      uniqueKey: ''
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    tableOutsideHeight() {
      return this.showMobilePage ? 210 : 250;
    },
    dataList() {
      const data = this.list.otherData || {};
      return [
        { label: '待结算总金额', data: data.settleAmount, icon: icon_16 },
        { label: '待结算成本数', data: data.beSettledCosts, icon: icon_17, isMoney: false, unit: '条' },
        { label: '下单日期', data: this.timeData.createOrderTime || '', icon: icon_20 },
        { label: '数据更新时间', data: this.timeData.updateTime, icon: icon_21 }
      ];
    },
    filterList() {
      const arr = [
        { keyword: 'account', name: '账号', labelWidth: '90px', type: 'input' },
        { keyword: 'accounts', name: '批量搜索账号', labelWidth: '100px', type: 'input', inputType: 'textarea',
          lengthLimit: false, placeholder: '可通过粘贴快速填写账号名称，每行代表一个账号名称' },
        { keyword: 'cooperation', name: '合作运营方', labelWidth: '90px', type: 'input' },
        { keyword: 'supplier', name: '供应商', labelWidth: '100px', type: 'input' },
        { keyword: 'settleAmount', name: '结算金额', labelWidth: '90px', type: 'inputRange',
          isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999 },
        { keyword: 'receivedAmount', name: '达人到手金额', labelWidth: '100px', type: 'inputRange',
          isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999 },
        { keyword: 'platformId', name: '下单平台', type: 'select', options: this.platformOption },
        { keyword: 'costSourceId', name: '成本来源', type: 'select', options: this.costOption }
      ];
      return arr;
    }
  },
  watch: {
    list: {
      handler(val) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val.items);
        });
      },
      deep: true
    }
  },
  created() {
    // this.setTimer(1500, true);
    this.id = Number(this.$route.params.id);
    this.followUsers = this.$route.query.followUsers;
    this.platformList();
    this.getTimeData();
    this.fetchData();
  },
  destroyed() {
    this.clearTimer();
  },
  methods: {
    async platformList() {
      try {
        const result = await platformList();
        result.data = result.data.map(item => {
          item = {
            value: item.id,
            label: item.value
          };
          return item;
        });
        result.data.unshift({ value: -2, label: '--' });
        this.platformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    async getTimeData() {
      try {
        const { data } = await getSettleTime(this.id);
        this.timeData = data;
      } catch (err) {
        console.log(err);
      }
    },
    formatParams(sendPageConfig = true) {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      paramsRangeFormat(this.rangeKeyArr, params);
      if (sendPageConfig) {
        params.page = this.page;
        params.perPage = this.perPage;
      }
      params.sortType = this.sortType;
      params.sortName = this.sortName;
      params.id = this.id;
      return params;
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = this.formatParams();
      this.listLoading = true;
      getSettleData(params).then((res) => {
        if (res.code === 200) {
          this.list = res.data;
        }
      }).catch(e => {
        console.error(e);
      }).finally(() => {
        this.list.isInit = false;
        this.listLoading = false;
      });
    },
    handleUpdate() {
      this.updateVisible = true;
    },
    closeUpdateDialog() {
      this.updateVisible = false;
    },
    btnStatus(val) {
      this.updateBtnLoading = val;
    },
    updateData() {
      this.updateVisible = false;
      this.getTimeData();
      this.queryEmpty();
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      if (this.clearMixinSelection) this.clearMixinSelection();
      this.fetchData(true);
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    handleSizeChange(perPage) {
      this.perPage = perPage;
      this.fetchData(true);
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    exportBeforeExport() {
      const params = this.formatParams();
      if (this.multipleSelectionAll.length) {
        params.ids = this.multipleSelectionAll.map(el => el.id).join(',');
      }
      this.$refs['moreOperateRef'] && this.$refs['moreOperateRef'].btnExport(params, 'exportRef');
    },
    // 结算操作
    handleSettle(row) {
      if (this.settleLoading) return;
      this.settleLoading = true;
      this.currentSettleId = row.id;
      accountSettleInfo({ settlementId: row.id }).then(res => {
        this.settleLoading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        localStorage.setItem('accountSettleData', JSON.stringify(res.data));
        this.$router.push({
          name: 'supplierCreate',
          query: {
            isInvite: 1,
            isAccountSettle: 1
          }
        });
      }).catch(err => {
        this.settleLoading = false;
        console.log(err);
      });
    },
    // 一键发起结算
    handleAllSettle() {
      this.$refs.BatchDialog.openDialog();
    },
    batchSettle(settleType = 1) {
      let ids = '';
      if (this.multipleSelectionAll.length) {
        ids = this.multipleSelectionAll.map(e => e.id).join(',');
      }
      this.batchSettleLoading = true;
      const data = Object.assign(this.formatParams(false), { settleType, ids });
      this.uniqueKey = this.generateKey();
      data.uniqueKey = this.uniqueKey;
      batchSettle(data).then(res => {
        if (res.code === 200) {
        // 开启轮询，获取更新情况
          if (!this.timer) {
            this.setTimer();
          }
        }
      }).catch(err => {
        this.batchSettleLoading = false;
        console.log(err);
      });
    },
    // 每隔一段时间去查询是否在更新信息
    setTimer(time = 1500, isInit) {
      this.timer = setInterval(() => {
        this.batchSettleStatus(isInit);
      }, time);
    },
    batchSettleStatus(isInit = false) {
      const data = {
        id: this.id,
        uniqueKey: this.uniqueKey
      };
      batchSettleStatus(data).then(res => {
        this.batchSettleInfo = res.data;
        const { status, total, settleNames } = res.data;
        if (status !== 1) { // 0无结算任务，1结算中，2结算成功，3结算失败
          this.clearTimer();
          !isInit && this.completeSettle(status, res.data.errMsg);
          this.batchSettleLoading = false;
        }
        if (status === 1 && total && this.$refs.LoadingDialog && !this.$refs.LoadingDialog.dialogVisible) {
          this.$refs.LoadingDialog.openDialog(settleNames, total);
        }
        this.multipleSelectionAll = [];
      }).catch(err => {
        this.batchSettleLoading = false;
        console.log(err);
        this.clearTimer();
      });
    },
    completeSettle(status, message) {
      if (status === 3 || status === 2) {
        const dialogType = status === 3 ? 0 : 1;
        this.$refs.LoadingDialog && this.$refs.LoadingDialog.handleClose();
        this.$refs.TipDialog.openDialog(dialogType, message);
        this.fetchData(true);
      }
    },
    // 搜素失败账号
    searchFailAccount(failAccountName = ' ') {
      this.paramsObj = {};
      const accounts = failAccountName.replace(/,/g, '\n');
      this.$set(this.paramsObj, 'accounts', accounts);
      this.fetchData(true);
    },
    // 刷新列表，清除定时器
    clearTimer() {
      clearInterval(this.timer);
      this.timer = null;
    },
    toSupplierDetail(id) {
      if (!id) return;
      const url = this.$router.resolve({
        name: 'supplierManageDetail',
        params: { id }
      });
      window.open(url.href, '_blank');
    },
    handleBack() {
      if (this.$route.query.fromDingDing) {
        this.$router.push({
          name: 'todo',
          query: { activeId: 3, fromDingDing: this.$route.query.fromDingDing }
        });
      } else {
        this.$router.push({
          name: 'todo',
          query: { activeId: 3 }
        });
      }
    },
    generateKey() {
      return new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999);
    }
  }
};
</script>

<style lang="scss" scoped>
.detail {
  .bottom-flex {
    width: 100%;
    display: flex;
    align-items: center;
    .back-btn {
      width:80px;
      height:30px;
    }
  }
}
.opeator-bar {
  display: flex;
  margin-bottom:16px;
  .flex-1 {
    flex: 1;
  }
}
.opeator-tool {
  display: flex;
  .btn {
    padding: 7px 15px;
    margin-right: 10px;
    margin-left: 0px;
  }
}
.tip-text {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #666;
  flex-shrink: 0;
  margin-right: 10px;
}
</style>
